package com.lq.ecoldchain.ui.main

import android.Manifest
import android.graphics.Color
import android.os.Build
import android.support.v4.app.FragmentManager
import android.view.KeyEvent
import com.alibaba.android.arouter.facade.annotation.Route
import com.lq.ecoldchain.R
import com.lq.ecoldchain.base.BaseNavigator
import com.lq.ecoldchain.base.view.BaseActivity
import com.lq.ecoldchain.common.FragmentViewPagerAdapter
import com.lq.ecoldchain.databinding.ActivityMainBinding
import com.lq.ecoldchain.util.ViewUtils
import com.lq.ecoldchain.util.toast
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*
import org.kodein.di.Kodein
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance

@Route(path = BaseNavigator.mainActivity)
class MainActivity : BaseActivity<ActivityMainBinding>() {
    override val kodein: Kodein = Kodein.lazy {
        extend(parentKodein)
        import(mainKodein)
        bind<FragmentManager>() with instance(supportFragmentManager)
    }

    override val layoutId = R.layout.activity_main

    override val viewDelegate: MainDelegate by instance()

    override fun initView() {
        nonFitSystem()
        if (Build.VERSION.SDK_INT >= 21) window.statusBarColor = Color.TRANSPARENT
        binding.delegate = viewDelegate
        titleGone()
        mainTabLayout.setupWithViewPager(mainViewPager)
        mainViewPager.adapter = FragmentViewPagerAdapter(supportFragmentManager, viewDelegate.fragments, viewDelegate.mainModel.titles)
        for (i in 0 until MainModel.views.size) {
            mainTabLayout.getTabAt(i)?.customView = MainModel.views[i]
        }
        val d = RxPermissions(this).request(Manifest.permission_group.LOCATION).subscribe {
            if (!it) {
                toast { "请到设置中开启定位权限,否则部分功能将无法正常使用" }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ViewUtils.exitTime(2000)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}
